import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as AddCustomerAction from '../../actions/addCustomer'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import CrmTools from '../crmTools'
import AddBatch from "./AddBatch"

import { WeaReqTop, WeaLeftRightLayout,WeaRightMenu,
    WeaSelect, WeaInput,WeaSearchGroup,WeaUpload, WeaTable } from 'ecCom'

import {WeaErrorPage,WeaTools} from 'ecCom'
const { getComponent } = WeaTools;

import {Button,Form,Row, Col,Table,Modal} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class AddCustomer extends React.Component {
    constructor(props) {
		super(props);
        _this = this;
        this.state={
            hasFile:"true",
            isrefresh:0
        }
    }
    componentDidMount() {
    	 const {actions,location} = this.props;
         actions.setNowRouterCmpath('addCustomer');
        if(!(JSON.stringify(location.query)=="{}")){
            actions.changeTabs(`${location.query.type}`);
        }
        actions.customerType();  //获取客户类型
       // actions.excelToDBInfo();  //获取批量导入基本信息
    }
    componentWillReceiveProps(nextProps) {
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
        if(keyOld!==keyNew) {
            const {actions,location} = this.props;
             actions.unmountClear();
            
            if(!(JSON.stringify(location.query)=="{}")){
                actions.changeTabs(`${location.query.type}`);
            }
           actions.customerType();  //获取客户类型
        //   actions.excelToDBInfo();  //获取批量导入基本信息
        }
    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.title,nextProps.title)||
        !is(this.props.selectKey,nextProps.selectKey)||
        !is(this.props.loading,nextProps.loading)||
        !is(this.props.orderFields,nextProps.orderFields)||
        !is(this.props.customerTypeList,nextProps.customerTypeList)||
        !is(this.props.customerAddForm,nextProps.customerAddForm)||
        !is(this.props.recordDatas,nextProps.recordDatas)||
        !is(this.props.columns,nextProps.columns)||
        !is(this.props.tooManyRecord,nextProps.tooManyRecord)||
        !is(this.props.noRecord,nextProps.noRecord)||
        !is(this.props.requiredAttr,nextProps.requiredAttr)||
        !is(this.props.defaultvalue,nextProps.defaultvalue)||
        !is(this.props.importdatas,nextProps.importdatas)||
        !is(this.props.searchParamsAd,nextProps.searchParamsAd)||
        !is(this.state,nextState);
    }
    componentWillUnmount(){
    	const {actions} = this.props;
        actions.unmountClear();
    }
    render() {
        let that = this;
        const {getFieldProps} = this.props.form;
        const {loading,actions,title,selectKey,customerTypeList,tooManyRecord,noRecord,columns,recordDatas,defaultvalue,importdatas} = this.props;
        const columns1 = columns.toJS();
        const recordDatas1 = recordDatas.toJS();
        const customerTypeList1 = customerTypeList.toJS();
        const tabDatas =[
            {title: '普通新建', key: "1"},
            {title: '批量导入', key: "2"}
        ];
        return (
            <div className="crm-top-req">
            	<WeaRightMenu datas={noRecord ? this.getRightMenu1() : this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                    <WeaReqTop 
                        title={title}
                        loading={loading}
                        icon={<i className='icon-coms-crm' />}
                        iconBgcolor='#96358a'
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        tabDatas={tabDatas}
                        selectedKey={selectKey}
                        onChange={this.changeTab.bind(this)}
                        showDropIcon={true}  
                        dropMenuDatas={this.getRightMenu()}
                        onDropMenuClick={this.onRightMenuClick.bind(this)}
                    >
                        {
                           selectKey == "1" && 
                           (!noRecord ?
                            <div>
                                <Form horizontal>
                                    <Row className="crm-add-row">
                                        <Col span="2">类型</Col>
                                        <Col span="22" className="crm-add-input">
                                            <WeaSelect {...getFieldProps("type", {
                                                initialValue:defaultvalue})} options={customerTypeList1} style={{width: 220}}/>
                                        </Col>
                                    </Row>
                                    <Row className="crm-add-row">
                                        <Col span="2">名称</Col>
                                        <Col span="22" className="crm-add-input">
                                            <WeaInput onPressEnter={()=>actions.myCustomerListForAdd()} {...getFieldProps("name")}  viewAttr={3} style={{width: 350}}/>
                                        </Col>
                                    </Row>
                                    <Row className="crm-add-row">
                                        <Col span="24">请输入客户名称，系统将搜索是否有重名客户。</Col>
                                    </Row>
                                    <Row className="crm-add-row">
                                        <Col span="24">如已有类似名称客户存在，系统将给出提醒，否则直接进入新建客户卡片页面。</Col>
                                    </Row>
                                </Form>
                               {
                                   tooManyRecord  ?
                                         <Row className="crm-add-row">
                                            <Col span="24" style={{color:"red"}}>搜索的结果太多无法显示! 请提供更精确的关键字搜索!</Col>
                                        </Row>:null
                               }
                               {
                                 ( recordDatas1.length>0 || tooManyRecord) &&
                                   <Table 
                                        className="crm-cusotmer-add-table"
                                        rowKey="id" 
                                        loading={false}
                                        columns={columns1}
                                        dataSource={recordDatas1}
                                        pagination={false} />
                               }
                            </div>: <div><Form horizontal>{this.getCreates()}</Form></div>)
                        }
                        {
                           selectKey == "2" &&  
                                <Form horizontal>
                                    <AddBatch hsaUploadState={this.hsaUploadState} key={this.state.isrefresh} initData={importdatas} actions={actions} params={this.props} />
                                </Form>
                        }
                    </WeaReqTop>
                </WeaRightMenu>
            </div>
        )
    }
    onRightMenuClick(key){
    	 const {actions,searchParamsAd} = this.props;
    	// const selectedRowKeys = comsWeaTable.get('selectedRowKeys');
    	if(key == '0'){
    		 actions.myCustomerListForAdd();
    	}
    	if(key == '1'){
    		 actions.searchCustomers();
    	}
    	if(key == '2'){
             actions.saveCustomers();
    	}
        if(key == '6'){
            const searchParamsAd1 = searchParamsAd.toJS();
            const require = function () {
                let bool = true;
                for (let key in searchParamsAd1) {
                    if (!searchParamsAd1[key]) {
                        bool = false;
                    }
                }
                return bool;
            }();
            if(require){
                if(this.state.hasFile == "false"){
                    window.startUploadAll();
                }else{
                    Modal.info({
                        title: '系统提示',
                        content: '请选择要导入的EXCEL文档！',
                    });
                }
            }else {
                Modal.warning({
                    title: '系统提示',
                    content: '必要信息不完整，红色标记为必填项！',
                });
            }
           
    	}
    }
    submitImport=()=>{
        const {actions,searchParamsAd} = this.props;
        const searchParamsAd1 = searchParamsAd.toJS();
        const require = function () {
            let bool = true;
            for (let key in searchParamsAd1) {
                if (!searchParamsAd1[key]) {
                    bool = false;
                }
            }
            return bool;
        }();
        if(require){
            if(this.state.hasFile == "false"){
                window.startUploadAll();
            }else{
                Modal.info({
                    title: '系统提示',
                    content: '请选择要导入的EXCEL文档！',
                });
            }
        }else {
            Modal.warning({
                title: '系统提示',
                content: '必要信息不完整，红色标记为必填项！',
            });
        }
    }
    getRightMenu(){
    	 const {actions,recordDatas,noRecord,selectKey} = this.props;
         const recordDatas2 = recordDatas.toJS();
    	let btns = [];
    	{ selectKey == "1" &&btns.push({
    		icon: <i className='icon-coms-search'/>,
    		content:'搜索',
            key:0
    	});}
        
         { selectKey == "1" && btns.push({
            icon: <i className='icon-coms-Revoke'/>,
            content:'继续',
            disabled: recordDatas2.length >0 ? false :true,
            key:1,
        });}
         { selectKey == "2" &&  btns.push({
    		icon: <i className='icon-coms-Approval '/>,
    		content:'提交',
            key:6
    	});}
        btns.push({
            icon: <i className='icon-coms-Collection'/>,
            content:'收藏',
            key:4
        });
    	btns.push({
            icon: <i className='icon-coms-help'/>,
            content:'帮助',
            key:5
        });
    	return btns
    }
    getRightMenu1(){
    	 const {actions,recordDatas,noRecord,} = this.props;
    	let btns = [];
       btns.push({
    		icon: <i className='icon-coms-Preservation'/>,
    		content:'保存',
             key:2
    	});
        btns.push({
    		icon: <i className='icon-coms-Revoke'/>,
    		content:'取消',
            key:3
    	});
      
        btns.push({
            icon: <i className='icon-coms-Collection'/>,
            content:'收藏',
            key:4
        });
    	btns.push({
            icon: <i className='icon-coms-help'/>,
            content:'帮助',
            key:5
        });
    	return btns
    }
   
    getButtons() {
        const {actions,noRecord,selectKey} = this.props;
        let btnArr = [];
          {
            selectKey =="1" && (noRecord ?  btnArr.push(<Button type="primary" onClick={()=>{actions.saveCustomers()}}>保存</Button>) :
                btnArr.push(<Button type="primary" onClick={()=>{ actions.myCustomerListForAdd();}}>搜索</Button>))
          }
          {
              selectKey == "2" && btnArr.push(<Button type="primary" onClick={this.submitImport}>提交</Button>)
          }
        return btnArr
    }

    changeTab(theKey) {
        const {actions} = this.props;
        actions.changeTabs(theKey);
    }
    getCreates() {
    	const { customerAddForm,actions } = this.props;
		let group = [];
        let viewObj = [];
		customerAddForm.toJS().map(c =>{
			let items = [];
			c.items.map(field => {
                let fit = field.formItemType.toUpperCase();
                if(fit == "INPUT" && field.viewAttr == "3" ||fit == "TEXTAREA" && field.viewAttr == "3"){
                    viewObj.push(field.domkey[0]);
                }else if(fit == "BROWSER"){
                    const bcp = field.browserConditionParam;
                    if(bcp.viewAttr == "3" &&  field.domkey[0] != "manager"){
                        viewObj.push(field.domkey[0]);
                    }  
                }
                if(fit== "ATTACHEMENT"){
                    items.push({
                        com:(<FormItem
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                            <WeaUpload
                                uploadId={field.domkey[0]}
                                uploadUrl="/api/crm/common/fileUpload"
                                category="0,0,0"
                                autoUpload={true}
                                showBatchLoad={false}
                                showClearAll={false}
                                multiSelection={true}
                                onChange={(ids,lists) => {this.onUploadChange(ids,lists,field.domkey[0])}}
                                onUploading={()=>this.uploadState()}
                            />
                            </FormItem>),
                        colSpan:1
                    })
                }else{
                    items.push({
                        com:(<FormItem
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                                { WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                            </FormItem>),
                        colSpan:1
                    })
                }
			});
			group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
		}); 
        actions.saveReqiuredAttr(viewObj);   //保存必填字段
		return group
    }
    onUploadChange(ids,lists,key){
       // console.log(ids,lists,key)
        let params = {};
        const {actions,orderFields} = this.props;
        params[key] = {
            "name":key,
            "value":`${ids}`
        }
        actions.saveOrderFields({...orderFields.toJS(), ...params})
    }
    uploadState=(state)=>{
       // console.log(state)
    }
    hsaUploadState=(state)=>{
    //  console.log("****",state);
        this.setState({hasFile:state});
        if(state=="uploaded"){
           this.setState({isrefresh:this.state.isrefresh+1})
        }
    }
}


class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

AddCustomer = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(AddCustomer);
//form 表单与 redux 双向绑定
AddCustomer = createForm({
	onFieldsChange(props, fields) {
        props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    },
	mapPropsToFields(props) {
		return props.orderFields.toJS();
  	}
})(AddCustomer);

function mapStateToProps(state) {
	const {addcustomer} = state;
    return  {
    	loading: addcustomer.get('loading'),
        title: addcustomer.get('title'),
        selectKey:addcustomer.get('selectKey'),
        orderFields:addcustomer.get('orderFields'),
        customerAddForm:addcustomer.get('customerAddForm'),
        customerTypeList:addcustomer.get('customerTypeList'),
        tooManyRecord:addcustomer.get('tooManyRecord'),
        noRecord:addcustomer.get('noRecord'),
        recordDatas:addcustomer.get('recordDatas'),
        columns:addcustomer.get('columns'),
        requiredAttr:addcustomer.get('requiredAttr'),
        defaultvalue:addcustomer.get('defaultvalue'),
        importdatas:addcustomer.get('importdatas'),
        searchParamsAd:addcustomer.get('searchParamsAd')
		//table
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...AddCustomerAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(AddCustomer);
